<template>
  <!-- 全局背景层 -->
  <view class="bg-layer"></view>
  
  <view class="container">
    <!-- 标题区域 -->
    <view class="header">
      <text class="title">用户管理</text>
      <text class="subtitle">系统用户管理</text>
      <view class="title-decoration"></view>
    </view>
    
    <!-- 表单卡片 -->
    <view class="form-card">
      <view class="form-bg"></view>
      <text class="form-title">{{ form._id ? '更新用户' : '添加新用户' }}</text>
      
      <!-- 表单输入区域 -->
      <view class="input-group">
        <uni-icons class="input-icon" type="person" size="18" color="#4a90e2"></uni-icons>
        <input 
          class="input" 
          v-model="form.username" 
          placeholder="用户名"
          placeholder-class="placeholder"
        />
      </view>
      
      <view class="input-group">
        <uni-icons class="input-icon" type="locked" size="18" color="#FF5252"></uni-icons>
        <input 
          class="input" 
          v-model="form.password" 
          type="password" 
          placeholder="密码"
          placeholder-class="placeholder"
        />
      </view>
      
      <view class="input-group">
        <uni-icons class="input-icon" type="contact" size="18" color="#4CAF50"></uni-icons>
        <input 
          class="input" 
          v-model="form.name" 
          placeholder="姓名"
          placeholder-class="placeholder"
        />
      </view>
      
      <!-- 角色选择器 -->
      <view class="picker-group">
        <uni-icons class="input-icon" type="staff" size="18" color="#9C27B0"></uni-icons>
        <picker 
          class="role-picker"
          @change="onRoleChange" 
          :value="roleIndex" 
          :range="roles"
        >
          <view class="picker-content">
            <text>{{ form.role || '选择角色' }}</text>
            <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
          </view>
        </picker>
      </view>
      
      <!-- 教师班级多选 -->
      <view class="picker-group" v-if="form.role === 'teacher'" @tap="showClassPicker('teacher')">
        <uni-icons class="input-icon" type="group" size="18" color="#CDDC39"></uni-icons>
        <view class="picker-content">
          <text>{{ form.className.length ? form.className.join(', ') : '选择可管理班级' }}</text>
          <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
        </view>
      </view>
      
      <!-- 学生信息字段 -->
      <template v-if="form.role === 'student'">
        <view class="input-group">
          <uni-icons class="input-icon" type="compose" size="18" color="#FF9800"></uni-icons>
          <input 
            class="input" 
            v-model="form.student_id" 
            placeholder="学号"
            placeholder-class="placeholder"
          />
        </view>
        
        <view class="input-group">
          <uni-icons class="input-icon" type="flag" size="18" color="#00BCD4"></uni-icons>
          <input 
            class="input" 
            v-model="form.major" 
            placeholder="专业"
            placeholder-class="placeholder"
          />
        </view>
        
        <!-- 学生班级单选 -->
        <view class="picker-group" v-if="classOptions.length" @tap="showClassPicker('student')">
          <uni-icons class="input-icon" type="group" size="18" color="#CDDC39"></uni-icons>
          <view class="picker-content">
            <text>{{ form.class_id || '选择班级' }}</text>
            <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
          </view>
        </view>
        
        <!-- 手动输入班级（无班级选项时） -->
        <view class="input-group" v-if="!classOptions.length">
          <uni-icons class="input-icon" type="group" size="18" color="#CDDC39"></uni-icons>
          <input 
            class="input" 
            v-model="form.class_id" 
            placeholder="输入班级（如 ClassA）"
            placeholder-class="placeholder"
          />
        </view>
      </template>
    </view>
    
    <!-- 提交按钮 -->
    <button 
      class="submit-button"
      @click="addOrUpdateUser"
      :disabled="!formValid"
      :class="{ 'disabled': !formValid }"
    >
      <view class="button-content">
        <uni-icons 
          :type="form._id ? 'redo' : 'plus'" 
          size="20" 
          color="#fff"
        ></uni-icons>
        <text>{{ form._id ? '更新用户' : '添加用户' }}</text>
      </view>
      <view class="button-wave" v-if="formValid"></view>
    </button>
    
    <!-- 班级选择弹窗 -->
    <uni-popup ref="classPopup" type="bottom">
      <view class="class-popup">
        <view class="popup-header">
          <text>选择班级</text>
          <uni-icons type="close" size="20" @tap="closeClassPicker"></uni-icons>
        </view>
        <scroll-view scroll-y class="class-list">
          <view v-for="item in classOptions" :key="item.value" class="class-item">
            <checkbox
              v-if="classPickerType === 'teacher'"
              :value="item.value"
              :checked="form.className.includes(item.value)"
              @tap="toggleClass(item.value)"
            />
            <radio
              v-else
              :value="item.value"
              :checked="form.class_id === item.value"
              @tap="selectClass(item.value)"
            />
            <text>{{ item.text }}</text>
          </view>
        </scroll-view>
        <button class="confirm-button" @tap="confirmClassPicker">确认</button>
      </view>
    </uni-popup>
    
    <!-- 用户列表 -->
    <scroll-view scroll-y class="user-list">
      <view v-if="loading" class="loading-state">
        <view class="spinner"></view>
        <text>加载中...</text>
      </view>
      
      <view v-else-if="!users.length" class="empty-state">
        <uni-icons type="info" size="24" color="#999"></uni-icons>
        <text>暂无用户数据</text>
      </view>
      
      <view 
        v-for="user in users" 
        :key="user._id" 
        class="user-card"
        :class="{
          'student-card': user.role === 'student',
          'teacher-card': user.role === 'teacher',
          'admin-card': user.role === 'admin'
        }"
      >
        <view class="user-info">
          <text class="user-name">{{ user.name }}</text>
          <view class="user-meta">
            <text class="username">@{{ user.username }}</text>
            <view class="role-badge" :class="user.role">
              {{ user.role === 'student' ? '学生' : 
                 user.role === 'teacher' ? '教师' : '管理员' }}
            </view>
          </view>
          <view v-if="user.role === 'student'" class="student-info">
            <text>{{ user.major }} · {{ user.class_id }}</text>
            <text>学号: {{ user.student_id }}</text>
          </view>
          <view v-if="user.role === 'teacher'" class="teacher-info">
            <text>管理班级: {{ user.className?.join(', ') || '无' }}</text>
          </view>
        </view>
        
        <view class="user-actions">
          <button 
            class="edit-button"
            @click="editUser(user)"
            :style="{ backgroundColor: roleColors[user.role] }"
          >
            <uni-icons type="compose" size="16" color="#fff"></uni-icons>
          </button>
          <button 
            class="delete-button"
            @click="deleteUser(user._id)"
          >
            <uni-icons type="trash" size="16" color="#fff"></uni-icons>
          </button>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      admin: {},
      form: {
        _id: '',
        username: '',
        password: '',
        name: '',
        role: '',
        student_id: '',
        major: '',
        class_id: '',
        className: [],
      },
      roles: ['student', 'teacher', 'admin'],
      classOptions: [],
      classPickerType: '', // 'student' 或 'teacher'
      roleColors: {
        student: '#4a90e2',
        teacher: '#9C27B0',
        admin: '#FF5252',
      },
      users: [],
      loading: false,
    };
  },
  computed: {
    formValid() {
      const required = ['username', 'password', 'name', 'role'];
      if (this.form.role === 'student') {
        required.push('student_id', 'major', 'class_id');
      }
      return required.every((field) => !!this.form[field]);
    },
    roleIndex() {
      return this.roles.indexOf(this.form.role);
    },
  },
  onLoad() {
    this.loadAdminData();
    this.loadUsers();
    this.loadClasses();
  },
  methods: {
    async loadAdminData() {
      this.admin = uni.getStorageSync('user') || {};
      if (!this.admin.id) {
        uni.navigateTo({ url: '/pages/student/login' });
      }
    },
    async loadClasses() {
      try {
        const res = await uniCloud.callFunction({
          name: 'manageUsers',
          data: { action: 'getClassList', data: {} },
        });
        if (res.result.code === 0) {
          this.classOptions = res.result.data.map((item) => ({
            value: item.value,
            text: item.label,
          }));
        } else {
          uni.showToast({ title: res.result.msg, icon: 'none' });
        }
      } catch (e) {
        uni.showToast({ title: '加载班级失败', icon: 'none' });
      }
    },
    async loadUsers() {
      try {
        this.loading = true;
        const res = await uniCloud.callFunction({
          name: 'manageUsers',
          data: { action: 'list', data: {} },
        });
        if (res.result.code === 0) {
          this.users = res.result.data;
        } else {
          uni.showToast({ title: res.result.msg, icon: 'none' });
        }
      } catch (e) {
        uni.showToast({ title: '加载用户失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },
    onRoleChange(e) {
      this.form.role = this.roles[e.detail.value];
      if (this.form.role !== 'teacher') {
        this.form.className = [];
      }
      if (this.form.role !== 'student') {
        this.form.class_id = '';
        this.form.student_id = '';
        this.form.major = '';
      }
    },
    showClassPicker(type) {
      this.classPickerType = type;
      this.$refs.classPopup.open();
    },
    closeClassPicker() {
      this.$refs.classPopup.close();
    },
    toggleClass(value) {
      const index = this.form.className.indexOf(value);
      if (index === -1) {
        this.form.className.push(value);
      } else {
        this.form.className.splice(index, 1);
      }
    },
    selectClass(value) {
      this.form.class_id = value;
    },
    confirmClassPicker() {
      this.$refs.classPopup.close();
    },
    async addOrUpdateUser() {
      const requiredFields = ['username', 'password', 'name', 'role'];
      if (this.form.role === 'student') {
        requiredFields.push('student_id', 'major', 'class_id');
      }
      if (requiredFields.some((field) => !this.form[field])) {
        uni.showToast({ title: '请输入完整信息', icon: 'none' });
        return;
      }
      try {
        // 规范化 class_id（统一小写，去空格）
        if (this.form.role === 'student' && this.form.class_id) {
          this.form.class_id = this.form.class_id.trim().toLowerCase();
        }
        const action = this.form._id ? 'update' : 'add';
        const data = { ...this.form };
        if (action === 'update' && !data.password) {
          delete data.password;
        }
        const res = await uniCloud.callFunction({
          name: 'manageUsers',
          data: { action, data },
        });
        if (res.result.code === 0) {
          uni.showToast({
            title: `${action === 'add' ? '添加' : '更新'}用户成功`,
            icon: 'success',
          });
          this.form = {
            _id: '',
            username: '',
            password: '',
            name: '',
            role: '',
            student_id: '',
            major: '',
            class_id: '',
            className: [],
          };
          this.loadUsers();
        } else {
          uni.showToast({ title: res.result.msg, icon: 'none' });
        }
      } catch (e) {
        uni.showToast({ title: '操作失败', icon: 'none' });
      }
    },
    editUser(user) {
      this.form = { ...user, password: '', className: user.className || [], class_id: user.class_id || '' };
    },
    async deleteUser(user_id) {
      uni.showModal({
        title: '确认删除',
        content: '此操作将永久删除该用户，是否继续？',
        confirmColor: '#FF5252',
        success: async (res) => {
          if (res.confirm) {
            try {
              const res = await uniCloud.callFunction({
                name: 'manageUsers',
                data: { action: 'delete', data: { _id: user_id } },
              });
              if (res.result.code === 0) {
                uni.showToast({ title: '删除用户成功', icon: 'success' });
                this.loadUsers();
              } else {
                uni.showToast({ title: res.result.msg, icon: 'none' });
              }
            } catch (e) {
              uni.showToast({ title: '删除失败', icon: 'none' });
            }
          }
        },
      });
    },
  },
};
</script>

<style scoped>
.container {
  position: relative;
  padding: 20px;
  min-height: 100vh;
  z-index: 1;
}

.bg-layer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 25vh;
  background: linear-gradient(135deg, #4a90e2 0%, #5aa1ff 100%);
  z-index: 0;
  border-radius: 0 0 20% 20%;
}

/* 标题区域 */
.header {
  position: relative;
  margin-bottom: 24px;
  text-align: center;
  padding: 16px 0;
}

.title {
  font-size: 24px;
  font-weight: 700;
  color: white;
  position: relative;
  z-index: 2;
  text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.subtitle {
  font-size: 14px;
  color: rgba(255,255,255,0.8);
  position: relative;
  z-index: 2;
  margin-top: 4px;
}

.title-decoration {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 160px;
  height: 100%;
  background: rgba(255,255,255,0.2);
  border-radius: 80px;
  filter: blur(12px);
  z-index: 1;
}

/* 表单卡片 */
.form-card {
  position: relative;
  background: rgba(255,255,255,0.95);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 10px 30px rgba(74, 144, 226, 0.15);
  margin-bottom: 24px;
  overflow: hidden;
}

.form-bg {
  position: absolute;
  top: 0;
  right: 0;
  width: 60%;
  height: 100%;
  background: linear-gradient(90deg, rgba(255,255,255,0) 0%, rgba(74, 144, 226, 0.05) 100%);
}

.form-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  position: relative;
  display: inline-block;
}

.form-title::after {
  content: '';
  position: absolute;
  bottom: -6px;
  left: 0;
  width: 40px;
  height: 3px;
  background: linear-gradient(90deg, #4a90e2, #5aa1ff);
  border-radius: 3px;
}

/* 输入框组 */
.input-group {
  position: relative;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  background: rgba(255,255,255,0.8);
  border-radius: 12px;
  padding-left: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  transition: all 0.3s;
}

.input-group:active {
  transform: scale(0.98);
}

.input-icon {
  margin-right: 10px;
  opacity: 0.7;
}

.input {
  flex: 1;
  height: 50px;
  font-size: 16px;
  color: #333;
  padding: 0 12px;
}

.placeholder {
  color: #aaa;
  font-size: 15px;
}

/* 选择器 */
.picker-group {
  position: relative;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  background: rgba(255,255,255,0.8);
  border-radius: 12px;
  padding-left: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  height: 50px;
}

.role-picker {
  flex: 1;
  height: 100%;
  display: flex;
  align-items: center;
  padding: 0 12px;
}

.picker-content {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #333;
}

/* 提交按钮 */
.submit-button {
  position: relative;
  width: 100%;
  height: 50px;
  background: linear-gradient(45deg, #4a90e2, #5aa1ff);
  color: white;
  border-radius: 12px;
  border: none;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(74, 144, 226, 0.3);
  transition: all 0.3s;
  margin-top: 12px;
}

.submit-button:active:not(.disabled) {
  transform: scale(0.98);
}

.submit-button.disabled {
  background: #e0e0e0;
  color: #9e9e9e;
  box-shadow: none;
}

.button-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  height: 100%;
  position: relative;
  z-index: 2;
}

.button-wave {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle, rgba(255,255,255,0.4) 0%, transparent 70%);
  opacity: 0;
  transition: opacity 0.5s;
}

.submit-button:not(.disabled):active .button-wave {
  opacity: 1;
}

/* 弹窗样式 */
.class-popup {
  background: #fff;
  border-radius: 12px 12px 0 0;
  padding: 16px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.class-list {
  max-height: 300px;
}

.class-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
}

.class-item text {
  margin-left: 8px;
  font-size: 14px;
  color: #333;
}

.confirm-button {
  background: #4a90e2;
  color: #fff;
  border-radius: 12px;
  margin-top: 12px;
  height: 40px;
  line-height: 40px;
}

/* 用户列表 */
.user-list {
  height: calc(100vh - 460px);
  padding-bottom: 20px;
}

.loading-state, .empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #999;
  font-size: 14px;
}

.empty-state text {
  margin-top: 8px;
}

.spinner {
  width: 24px;
  height: 24px;
  border: 3px solid rgba(74, 144, 226, 0.3);
  border-radius: 50%;
  border-top-color: #4a90e2;
  animation: spin 1s linear infinite;
  margin-bottom: 8px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 用户卡片 */
.user-card {
  background: rgba(255,255,255,0.95);
  border-radius: 16px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  transition: all 0.3s;
}

.user-card:active {
  transform: scale(0.98);
}

.student-card {
  border-left: 4px solid #4a90e2;
}

.teacher-card {
  border-left: 4px solid #9C27B0;
}

.admin-card {
  border-left: 4px solid #FF5252;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.user-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}

.username {
  font-size: 12px;
  color: #999;
}

.role-badge {
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  color: white;
}

.role-badge.student {
  background: #4a90e2;
}

.role-badge.teacher {
  background: #9C27B0;
}

.role-badge.admin {
  background: #FF5252;
}

.student-info, .teacher-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
  font-size: 12px;
  color: #666;
}

/* 用户操作按钮 */
.user-actions {
  display: flex;
  gap: 8px;
}

.edit-button, .delete-button {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
  transition: all 0.3s;
}

.edit-button:active, .delete-button:active {
  transform: scale(0.9);
}

.edit-button {
  background: #4a90e2;
}

.delete-button {
  background: #FF5252;
}
</style>